package com.sharemedia.views
{
	import com.sharemedia.skins.defaultSkin.RatingStarsSkin;
	import com.sharemedia.utils.SkinUtil;
	
	import flash.events.Event;
	
	import mx.core.IVisualElement;
	import mx.effects.Effect;
	import mx.events.ResizeEvent;
	
	import spark.components.supportClasses.Range;
	import spark.components.supportClasses.SkinnableComponent;
	
	/**
	 * UI Component that shows rating stars.  
	 */	
	public class RatingStars extends Range
	{
		// Set default skin
		SkinUtil.setSkin("com.sharemedia.views.RatingStars", RatingStarsSkin);
		
		[SkinPart]
		/**
		 * Area that will be filled accordingly to rating. 
		 */		
		public var filledArea:IVisualElement;
		
		[SkinPart]
		/**
		 * Area that used as fill accordingly to rating. 
		 */		
		public var fillArea:IVisualElement;
		
		[SkinPart]
		/**
		 * Effect on change value. 
		 */		
		public var changeEffect:Effect;
		
		/**
		 * Constructor. 
		 */		
		public function RatingStars()
		{
			super();
		}
		
		/**
		 * @inheritDoc 
		 */		
		override protected function partAdded(partName:String, instance:Object):void
		{
			super.partAdded(partName, instance);
			
			if(instance == filledArea)
			{
				updateSkinDisplayList();
				filledArea.addEventListener(ResizeEvent.RESIZE, filledArea_resizeHandler);
			}
				
			else if(instance == fillArea)
			{
				updateSkinDisplayList();
			}
		}
		
		/**
		 * @inheritDoc 
		 */
		override public function set value(newValue:Number):void
		{
			if(changeEffect && value!=newValue)
				changeEffect.play();
			
			super.value = !isNaN(newValue) ? newValue : 0;
		}
		
		/**
		 * @inheritDoc 
		 */	
		override protected function partRemoved(partName:String, instance:Object):void
		{
			super.partRemoved(partName, instance);
			
			if(instance == filledArea)
			{
				filledArea.removeEventListener(ResizeEvent.RESIZE, filledArea_resizeHandler);
			}
		}
		
		/**
		 * @inheritDoc 
		 */	
		override protected function setValue(value:Number):void
		{
			super.setValue(value);
			
			updateSkinDisplayList();
		}
		
		/**
		 * Resize handler for filledArea 
		 */		
		private function filledArea_resizeHandler(event:Event):void
		{
			updateSkinDisplayList();
		}
		
		/**
		 * Update fill area. 
		 */		
		protected function updateSkinDisplayList():void
		{
			if(filledArea && fillArea)
				fillArea.setLayoutBoundsSize(calculateAreaSize(), filledArea.getLayoutBoundsHeight());
		}
		
		/**
		 * Calculate fill are width. 
		 */		
		private function calculateAreaSize():Number
		{
			var areaWidth:Number = filledArea.getLayoutBoundsWidth();
			
			var range:Number = maximum - minimum;
			var size:Number = (range > 0) ? (value - minimum) * (areaWidth / range) : 0;
			
			return Math.round(size);
		}
	}
}